import { CommonModule } from '@/store/modules/common'
import { deepClone, commonAction } from '@/utils/common';
/**
 * 公告管理
 */
interface DefaultForm {
  id?: string
  title: string
  content: string
  attachs: any
  showDays: any
  level: string
  showScope: any
}

interface PageData {
  total: number
  limit: number
  page: number
}
const getDept: any = async () => {
  let department: any = []
  let companyName: string = ''
  const flatMap = (data: any) => {
    data.map(v => {
      department.push({
        id: v._id,
        label: v.name,
        pid: v.parentId
      })
      if (v.children && v.children.length > 0) {
        flatMap(v.children)
      }
    })
  }
  try {
    const result: any = await CommonModule.getDepartmentTree()
    flatMap(result.tree)
    companyName = result.companyName
  } catch (e) {
    department = []
  }
  return {
    department,
    companyName
  }
}

/**
 * 渲染公式范围树选择
 * @param data
 * @returns
 */
const renderTree = async (oridata: any) => {
  const tree = [
    { id: 111, pid: 0, label: '角色', field: 'role', disabled: false, children: [] },
    { id: 222, pid: 0, label: '技能组', field: 'queue', disabled: false, children: [] },
    { id: 333, pid: 0, label: '座席', field: 'user', disabled: false, children: [] },
    { id: 444, pid: 0, label: '部门', field: 'dept', disabled: false, children: [] }
  ]
  const transferFromData: any = deepClone(tree);
  const visiblePersonnel: any = deepClone(tree);
  const data = {
    role: oridata.role.split(','),
    queue: oridata.queue.split(','),
    user: oridata.user.split(','),
    dept: oridata.dept.split(',')
  }
  if (data) {
    for (const v of (CommonModule as any).publicCache.roleList) {
      if (data.role.includes(v._id)) {
        visiblePersonnel[0].children.push({
          id: v._id,
          pid: 111,
          label: v.name
        })
      } else { // 未选，左侧
        transferFromData[0].children.push({
          id: v._id,
          pid: 111,
          label: v.name
        })
      }
    }
    for (const v of (CommonModule as any).publicCache.queueList) { // 技能组
      if (data.queue.includes(v._id)) { // 已选，右侧
        visiblePersonnel[1].children.push({
          id: v._id,
          pid: 222,
          label: v.name
        })
      } else { // 未选，左侧
        transferFromData[1].children.push({
          id: v._id,
          pid: 222,
          label: v.name
        })
      }
    }
    for (const v of (CommonModule as any).publicCache.userList) { // 座席
      if (data.user.includes(v._id)) { // 已选，右侧
        visiblePersonnel[2].children.push({
          id: v._id,
          pid: 333,
          label: v.agentName + ' [' + v.agentNumber + ']'
        })
      } else { // 未选，左侧
        transferFromData[2].children.push({
          id: v._id,
          pid: 333,
          label: v.agentName + ' [' + v.agentNumber + ']'
        })
      }
    }
    const { department } = await getDept()
    for (const v of department) { // 技能组
      if (data.dept.includes(v._id)) { // 已选，右侧
        visiblePersonnel[3].children.push({
          id: v.id,
          pid: 444,
          label: v.label
        })
      } else { // 未选，左侧
        transferFromData[3].children.push({
          id: v.id,
          pid: 444,
          label: v.label
        })
      }
    }
  }
  return {
    transferFromData,
    visiblePersonnel
  }
}

/**
 * 构造层级树
 * @param data
 * @param item
 */
const renderDepartment = (data: any, item: any) => {
  const res: any = data.filter(v => v.pid === item.id).map(v => {
    return {
      id: v.id,
      label: v.label
    }
  })
  item.children = res
  res.map(v => {
    renderDepartment(data, v)
  })
}

const renderDepartmentAndAgent = (data: any, agent: any, item: any) => {
  const res: any = data.filter(v => v.pid === item.id).map(v => {
    return {
      label: v.label,
      id: v.id,
      type: 'dept'
    }
  })
  const ag = agent.filter(v => v.dept.includes(item.id))
  item.children = [...ag, ...res]
  res.map(v => {
    renderDepartmentAndAgent(data, agent, v)
  })
}

const getTreeCount = (tree: any) => {
  const ags = tree.children.filter(v => v.type === 'agent')
  const depts = tree.children.filter(v => v.type === 'dept')
  if (depts.length === 0) {
    tree.count = ags.length
    return ags.length
  } else {
    let count = ags.length
    depts.map(v => {
      count = count + getTreeCount(v)
    })
    tree.count = count
    return count
  }
}

const filterTree = (tree: any) => {
  if (tree.children) {
    tree.children = tree.children.filter(v => {
      if (v.type === 'dept') {
        if (v.count > 0) {
          return true
        } else {
          return false
        }
      } else {
        return true
      }
    })
    tree.children.map(v => {
      filterTree(v)
    })
  }
}

const treeResult = async (showScope: any) => {
  const agents = getAllAgents(showScope)
  const { department, companyName } = await getDept()
  const newDept = { id: '', label: companyName }
  renderDepartmentAndAgent(department, agents, newDept)
  getTreeCount(newDept)
  filterTree(newDept)
  return newDept
}

const getAllAgents = (showScope: any) => {
  const data = (CommonModule as any).publicCache.userList
  const len = data.length
  const res: any = []
  for (let i = 0; i < len; i++) {
    let departmentId: any = []
    if (data[i].departmentConfig) {
      departmentId = data[i].departmentConfig.departmentIdList
    }
    if (departmentId.length === 0) {
      departmentId = ['']
    }
    const temp = {
      label: data[i].agentName + '<span style="margin-left:5px"></span>[' + data[i].agentNumber + ']',
      id: data[i]._id,
      type: 'agent',
      dept: departmentId
    }
    if (showScope.user.includes(data[i]._id)) {
      res.push(temp)
      continue
    }
    if (data[i].roles.some(v => showScope.role.includes(v))) {
      res.push(temp)
      continue
    }
    if (data[i].queueList.some(v => showScope.queue.includes(v))) {
      res.push(temp)
      continue
    }
    if (departmentId.some(v => showScope.dept.includes(v))) {
      res.push(temp)
      continue
    }
  }
  return res
}

const fileSizePretty = (size: number) => {
  let result = ''
  size = size / 1024
  if (size < 1024) {
    result = size.toFixed(2) + 'KB'
  } else if (size < 1024 * 1024) {
    result = (size / 1024).toFixed(2) + 'MB'
  } else {
    result = (size / 1024 / 1024).toFixed(2) + 'GB'
  }
  return result
}

export {
  DefaultForm,
  PageData,
  renderTree,
  treeResult,
  fileSizePretty
}
